import java.awt.Color;
import java.awt.Graphics;
import java.util.concurrent.Semaphore;

public class Ball extends Thread {

    private Semaphore terminate;
	private String name;
	
	BallWorld world;
    
    private int xpos, ypos, xinc, yinc;

    private final Color col;

    private final static int ballw = 10;
    private final static int ballh = 10;
    
    public Ball(String name, Semaphore sem, BallWorld world, int xpos, int ypos, 
		int xinc, int yinc, Color col) {
		//
		// Assign a name to this thread for easier debugging
		//
		super("Ball :"+col);
	
		this.world = world;
	    this.xpos = xpos; this.ypos = ypos;
		this.xinc = xinc; this.yinc = yinc;
	    this.col = col;
	
	    terminate = sem;
	    this.name = name;
	    
	    world.addBall(this);
	    
	    
	    
    }
    
    public void run() {
		while (true){
			
			while(!terminate.tryAcquire())
				move();
			//the process has the semaphore
			//remove the ball
			world.removeBall(this);
			//Balls.nap((int)(800*Math.random()));
			System.out.println(this.name + " Before: " + terminate.toString());
			terminate.release();
			System.out.println(this.name + " After: " + terminate.toString());
		}
    }
   
    public void move() {
		if (xpos >= world.getWidth() - ballw || xpos <= 0 ) xinc = -xinc;
		
		if (ypos >= world.getHeight() - ballh || ypos <= 0 ) yinc = -yinc;
	
		Balls.nap(30);
		doMove();
		world.repaint();
    }
     
    //
    // SYNC: This modifies xpos and ypos.
    //
    public synchronized void doMove() {
		xpos += xinc;
		ypos += yinc;
    }

    //
    // SYNC: This is accessed from the GUI thread, and
    //       it reads xpos and ypos.
    //
    public synchronized void draw(Graphics g) {
		g.setColor(col);
		g.fillOval(xpos,ypos,ballw,ballh);
    }
}
